package com.erik.lin.kafka;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

import java.util.Arrays;
import java.util.Properties;

/**
 * Created by Erik on 2017/7/27.
 */
public class DataExKafkaConsumer implements Runnable {

    private String topic;

    private String bootStrapServers;

    private String groupId;

    public DataExKafkaConsumer(String topic, String bootStrapServers, String groupId) {
        this.topic = topic;
        this.bootStrapServers = bootStrapServers;
        this.groupId = groupId;
    }

    @Override
    public void run() {
        Properties props = new Properties();
        props.put("bootstrap.servers", bootStrapServers);
        props.put("group.id", groupId);
        props.put("enable.auto.commit", "false");
        props.put("auto.commit.interval.ms", "1000");
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
        consumer.subscribe(Arrays.asList(topic));
        while (true) {
            ConsumerRecords<String, String> records = consumer.poll(100);
            for (ConsumerRecord<String, String> record : records) {
                System.out.printf("offset = %d, partition = %s, value = %s%n", record.offset(), record.partition(), record.value());
            }
            consumer.commitSync();
        }

    }

    public static void main(String[] args) {
        new Thread(new DataExKafkaConsumer("test", "192.168.8.8:9092,192.168.8.8:9093,192.168.8.8:9094", "group1")).start();
    }
}
